package com.unlcn.ils.wms.backend.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class SoapUtil {

	/**
	 * 转换返回结果为map
	 * 
	 * @param responseList
	 * @return
	 * @throws DocumentException
	 */
	public static String getResponseMap(String responseList) throws DocumentException {
		responseList = responseList.replace("&lt;", "<").replace("&gt;", ">");
		responseList = responseList.replaceAll("&", "&amp;");
		Document doc = DocumentHelper.parseText(responseList);

		Map map = Dom2Map(doc);
		/*for (Object key : map.keySet()) {
	        System.out.println("key= " + key + " and value= " + map.get(key));
	    }*/
		return ((Map<String, String>) ((Map) map.get("Body")).get("excuteServiceResponse")).get("excuteServiceReturn");
	}

	/**
	 * Document 转map
	 * 
	 * @param doc
	 * @return
	 */
	public static Map<String, Object> Dom2Map(Document doc) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (doc == null)
			return map;
		Element root = doc.getRootElement();
		map = Dom2Map(root);
		return map;
	}

	/**
	 * Element转map
	 * 
	 * @param e
	 * @return
	 */
	public static Map Dom2Map(Element e) {
		Map map = new HashMap();
		List list = e.elements();
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Element iter = (Element) list.get(i);
				List mapList = new ArrayList();

				if (iter.elements().size() > 0) {
					Map m = Dom2Map(iter);
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(m);
						}
						if (obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = (List) obj;
							mapList.add(m);
						}
						map.put(iter.getName(), mapList);
					} else
						map.put(iter.getName(), m);
				} else {
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(iter.getText());
						}
						if (obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = (List) obj;
							mapList.add(iter.getText());
						}
						map.put(iter.getName(), mapList);
					} else
						map.put(iter.getName(), iter.getText());
				}
			}
		} else
			map.put(e.getName(), e.getText());
		return map;
	}
}
